﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Data.Services.Client;

namespace StorageAbstraction.Tables
{
    public class CompletedTasksDataContext : TableServiceContext
    {
        public CompletedTasksDataContext(string baseAddress, StorageCredentials credentials)
            : base(baseAddress, credentials)
        {
            this.RetryPolicy = RetryPolicies.RetryExponential(1, TimeSpan.FromSeconds(2));
        }

        /// <summary>
        /// This is required publicp roperty for the CloudTableClient.CreateTablesFromModel to work properly
        /// </summary>
        public IQueryable<CompletedTaskEntry> CompletedTaskEntry
        {
            get
            {
                return this.CreateQuery<CompletedTaskEntry>("CompletedTaskEntry");
            }
        }

        internal void AddCompletedTask(CompletedTaskEntry entry)
        {
            entry.RowKey = entry.TaskId.ToString();
            this.AddObject("CompletedTaskEntry", entry);
            this.SaveChanges();
        }

        internal CompletedTaskEntry GetCompletedTask(Guid taskId)
        {
            CompletedTaskEntry result = null;
            try
            {
                var res = from ct in this.CompletedTaskEntry
                          where
                            ct.PartitionKey == "ConvertedVideos"
                            && ct.RowKey == taskId.ToString()
                          select ct;
                result = res.FirstOrDefault<CompletedTaskEntry>();
            }
            catch (DataServiceQueryException dsqe)
            {
                // just do nohting the record isnt there ?
            }
            return result;
        }
    }
}
